package com.psy.counseling.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.util.PoitlIOUtils;
import com.psy.counseling.entity.Ask;
import com.psy.counseling.mapper.FirstVisitMapper;
import com.psy.counseling.service.AskService;
import com.psy.counseling.utils.Result;
import com.psy.counseling.utils.WordUtil;
import com.psy.counseling.vo.AnalysisVO;
import com.psy.counseling.vo.DeleteVO;
import com.psy.counseling.vo.PageVO;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.zip.ZipOutputStream;

/**
 *咨询结果记录
 * @author 陈兴海
 * @since 2022-05-29
 */
@RestController
@RequestMapping("/api/analysis")
public class AnalysisController {

    @Autowired
    private AskService askService;
    @Autowired
    private FirstVisitMapper firstVisitMapper;

    /**
     * 通过咨询报告id导出word
     * @param id
     * @param response
     * @param templatePath
     * @throws IOException
     */
    @GetMapping("/askDownLoad/{id}")
    public void askDownLoad(@PathVariable("id") Long id, HttpServletResponse response, @Value("${word_path}")String templatePath) throws IOException {
        Ask ask = askService.getById(id);
        if(ask!=null){
            response.setContentType("application/octet-stream;charset=UTF-8");
            String fileName = ask.getRealName()+"咨询报告.docx";
            response.setHeader("Content-disposition", "attachment;filename=\"" + new String(fileName.getBytes("gb2312"), "ISO8859-1") + "\"");
            OutputStream out = response.getOutputStream();
            XWPFTemplate template = WordUtil.toWord(ask, templatePath);
            BufferedOutputStream bos = new BufferedOutputStream(out);
            template.write(bos);
            bos.flush();
            out.flush();
            PoitlIOUtils.closeQuietlyMulti(template, bos, out);
            out.close();
            bos.close();
            template.close();
        }
    }

    /**
     * 批量下载文件，将文件压缩为一个压缩包
     * @param idVO
     * @param response
     * @param templatePath
     * @throws IOException
     */
    @PostMapping("/batchAskDownLoad")
    public void batchAskDownLoad(@RequestBody DeleteVO idVO,HttpServletResponse response,@Value("${word_path}")String templatePath) throws IOException {
        String zipFilePath = templatePath.substring(0,templatePath.lastIndexOf("/")+1)+"咨询报告.zip";
        String filePath = templatePath.substring(0,templatePath.lastIndexOf("/")+1);
        if(idVO.getIds().size()>0){
            List<Ask> asks = askService.listByIds(idVO.getIds());
            for (Ask ask : asks){
                WordUtil.toWord(ask,templatePath).writeAndClose(new FileOutputStream(filePath+ask.getRealName()+"咨询报告.docx"));
            }

            ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFilePath));
            for (Ask ask : asks){
                WordUtil.fileToZip(filePath+ask.getRealName()+"咨询报告.docx",zipOut);
                new File(filePath+ask.getRealName()+"咨询报告.docx").delete();
            }
            zipOut.close();
            String fileName = new String(("咨询报告压缩文件.zip").getBytes(),"ISO-8859-1");
            response.setHeader("Content-Disposition", "attchment;filename="+fileName);
            ServletOutputStream outputStream = response.getOutputStream();
            FileInputStream inputStream = new FileInputStream(zipFilePath);
            IOUtils.copy(inputStream, outputStream);
            inputStream.close();
            File fileTempZip = new File(zipFilePath);
            fileTempZip.delete();
        }
    }


    /**
     * 获取咨询师的总咨询次数和咨询时间
     * @param teacherName
     * @return
     */
    @GetMapping("/getAskTeacherInfo/{teacherName}")
    public Result<List<AnalysisVO>> getAskTeacherInfo(@PathVariable("teacherName")String teacherName){
        List<AnalysisVO> teacherInfo = askService.getAskTeacherInfo(teacherName);
        return Result.success(teacherInfo);
    }

    /**
     * 通过学生和老师的真实姓名查找咨询记录
     * @param userName
     * @param teacherName
     * @param pageVO
     * @return
     */
    @GetMapping("/getAskInfo/{userName}/{teacherName}")
    public Result<Page<Ask>> getAskInfo(@PathVariable String userName, @PathVariable String teacherName, PageVO pageVO){
        Page<Ask> page = new Page<>(pageVO.getPageNum(),pageVO.getPageSize());
        page = askService.getAskInfo(userName,teacherName,page);
        return Result.success(page);
    }
}

